var json1;
var senCurtime ;
var video = $("#player");
var videoId = location.search.split("=")[1];
var imgid = 1;    //从session里面获取
var noteTitle;
var noteCont;
var getUid = $("#uid").val();

//点击跳出当前页面，发出的保存信息的请求
 window.onbeforeunload = function(){  
		$.ajax({

			type : 'post',
			url : 'browse_save',
			data : {
                videoid:videoId,
                uid:getUid,  //从session里面取
                videoDot:senCurtime  
            }

		});
	  }

$(function(){
    /*点击评论添加*/
    $("#comment-sub1").click(function(){
        var time = new Date();
        var day = time.getMonth()+1 +"-"+time.getDate()+" "+time.getHours()+":"+time.getMinutes();
        
        
        
        var comments = $("#submit-comm1").val();
        //alert(comments);
        if(comments ==null || comments == ""){
            alert("请填写评论");
        }else{
            $("#ans_box").after("<div class='ques'><img src='images/usericon/user"+imgid+".jpg'><div><div class='quser'><a href='#'>用户姓名</a><span>"+day+"</span></div><div class='qtit'>"+comments+"</div><div class='qcount'>0回答</div></div></div>");
            $.ajax({
                type:"post",
                url :"discuss_addquestion",
                dataType : "json",
                data:{
                    uid:getUid,
                    videoid:videoId,
                    content:comments
                }
                
            })
        }
    });
    
    /*笔记*/
    $(".notes").on("click","#comment-sub2",function(){
        var time = new Date();
        var day = time.getMonth()+1 +"-"+time.getDate()+" "+time.getHours()+":"+time.getMinutes();
        var noteTitle = $("#comments-title").val();
        var noteCont = $("#submit-comm2").val();
        alert(noteCont+"..."+noteTitle);
        if(noteTitle ==null || noteTitle == "" || noteCont == null || noteCont == ""){
            alert("请填写笔记标题和内容");
        }else{
            $("#notes_box").after("<div class='note'><img src='images/usericon/user"+imgid+".jpg'><div><div class='noter'><a href='#'>用户名</a><span>"+day+"</span><span class='note_tit'>"+noteTitle+"</span></div><div class='notecont'><span>"+noteCont+"</span><span id='notefor' isfor=true><span class='iconfont icon-dianzan'></span><span id='fornum'>0</span></span></div></div></div>");
            $.ajax({
               type:"post",
               url:"note_addNote",
               dataType:"json",
               data:{
                  videoid:videoId,
                  uid:getUid,   //从session里面取
                  noteTitle:noteTitle,
                  noteCont:noteCont
               }
            })
        }
    });
})

    
    $(function(){
        
        
        console.log("视频id"+videoId);
        
         $.ajax({
        	type:"get",
        	url:"video_detail",
        	dataType:"json",
        	data:{
                videoId:videoId,
                uid:getUid
            },
        	success:function(data){
                json1 = data;
        		//console.log(data);
                console.log(json1.rec);
                
                $(".classname").html(json1.classname);
                $(".classlist").html(json1.classlist);
                $("#player").attr("src",json1.src);
                curtime =json1.curTime;
                
                var $append = "<div class='recomm_msg'><span>推荐课程</span></div>";
                $.each(json1.rec, function(index,val){
                	$append += "<div class='classes_recom'><a href='ResHome.jsp?courseId="+val[1]+"'>"+val[0]+"</a></div>";
                })
                
                $(".recommend").html($append);
                
                
                $(".notes").hide();
                //显示问答列表
                var quelen=json1.question.length;
                for(var i=0;i<quelen;i++){
                    if(json1.question[i][4] == null){
                        $(".QaA").append("<div class='ques'><img src='images/usericon/user"+json1.question[i][1]+".jpg'><div><div class='quser'><a href='comments.jsp?queId="+json1.question[i][6]+"'>"+json1.question[i][0]+"</a><span>"+json1.question[i][2]+"</span></div><div class='qtit'>"+json1.question[i][3]+"</div><div class='qcount'>"+json1.question[i][5]+"回答</div></div></div>");
                    }else{
                        $(".QaA").append("<div class='ques'><img src='images/usericon/user"+json1.question[i][1]+".jpg'><div><div class='quser'><a href='comments.jsp?queId="+json1.question[i][6]+"'>"+json1.question[i][0]+"</a><span>"+json1.question[i][2]+"</span></div><div class='qtit'>"+json1.question[i][3]+"</div><div class='qans'><span>[最新回答]</span><span>"+json1.question[i][4]+"</span></div><div class='qcount'>"+json1.question[i][5]+"回答</div></div></div>");
                    }
                }
                
        	},
        	error:function(){
        		console.log("请求视频数据出错");
        	}
        })
        
            
         
    /*点击问答和笔记请求数据*/
    //-------------------点击问答
    $(".navq").click(function(){
        $(this).addClass("color");
        $(".navnote").removeClass("color");
        $(".QaA").show();
        $(".notes").hide();
    
         /*为问答赋值*/
       // $(".QaA").empty();
    });
    
    
     //---------------点击笔记-------------//
    $(".navnote").click(function(){
        $(this).addClass("color");
        $(".navq").removeClass("color");
        $(".notes").show();
        $(".QaA").hide();
        
        $(".notes").empty();
        $(".notes").append("<div class='ques commentsbox' id='notes_box'><div class='comment-msg'>评论:</div><input type='text' class='comments-title' placeholder='请输入笔记标题' id='comments-title'><div class='comment-box'><img src='' alt=''><textarea id='submit-comm2' cols='30' rows='10' ></textarea><button id='comment-sub2'>提交</button></div></div>");
        
        
        
        $.ajax({
           type:"post",
           url:"note_detail",
           dataType:"json",
           data:{
              courseid:18     //视频id
           },
           success:function(data){
                //为笔记赋值
                var notelen=data.note.length;
                if(notelen >0){
                    for(var i=0;i<notelen;i++){
                        $(".notes").append("<div class='note'><img src='images/usericon/user"+data.note[i][1]+".jpg'><div><div class='noter'><a href='#'>"+data.note[i][0]+"</a><span>"+data.note[i][2]+"</span><span class='note_tit'>"+data.note[i][3]+"</span></div><div class='notecont'><span>"+data.note[i][4]+"</span><span id='notefor' class="+data.note[i][6]+" isfor=true><span class='iconfont icon-dianzan'></span><span id='fornum'>"+data.note[i][5]+"</span></span></div></div></div>");
                    }
                    //绑定点击事件
                    $(".notecont>span").each(function(){
                        $(this).on("click",show);
                    });
                }
               
           },
           error:function(){
               //alert("navq error");
           }
        });

    });
    
    
    
    var forflag = true;
    function show(){     
        /*点赞笔记和取消点赞*/
        //alert(forflag);
        if($(this).attr("isfor") == "true"){
            $($(this).find("#fornum").prev()).css({"color":"#000"});
            var num=parseInt($($(this).find("#fornum")).html());
            $($(this).find("#fornum")).html(++num);
            $($(this).find("#fornum")).css({"color":"#000","transition":"all 0.3s ease-in"});
            $(this).attr("isfor",false);
        }
        $.ajax({
            type:"post",
            url:"note_agree?noteId="+$(this).attr("class"),
        })
    }

      
        
		//转圈圈，加载
		//$(".loading").fadeIn(500);
		video.on("loadedmetadata", function(){
            
            if(curtime == 0){
                $("#current").text(timeFormat1(0));
            }else{
                $("#current").text(timeFormat1(curtime));
            }
			
			$("#duration").text(timeFormat1(video[0].duration));
            updatebar1(json1.curTime);
			updateVolume(0,0.7);
			
			//延迟150ms启动缓存
			setTimeout(startBuffer, 150);
			
			$("section")
			.append("<div id='init'></div>")
			.on("click", function(){
				$("#init").remove();
				$("#video-btn").addClass("paused");
				//解绑
				$(this).unbind("click");
				video[0].play();
			});
			
			$("#init").fadeIn(200);
		});
		
        //获取视频的总时长以及当前时间
		video.on("timeupdate", function(){
			var currentPos = video[0].currentTime;
			var maxduration = video[0].duration;
			var perc = 100*currentPos/maxduration;
			$(".timeBar").css("width",perc+"%");
            $('.yuandian').css({"margin-left":perc-0.2+'%'});
			$("#current").text(timeFormat1(currentPos));
            
            if(video[0].currentTime == video[0].duration){
                $("#video-btn").removeClass("paused");
				video[0].pause();
            }
		});
		
		//直接电视视频对象和点击播放按钮是相同的效果
		video.on("click",function(){ playpause();});
		$("#video-btn").on("click", function(){ playpause(); });
		
		//播放事件
		var playpause = function(){
			if(video[0].paused || video[0].ended){
				$("#video-btn").addClass("paused");
				video[0].play();
				
			}else{
				$("#video-btn").removeClass("paused");
				video[0].pause();
			}
		};
		
		
		
		//全屏点击
		$(".btnFS").on("click", function(){
			if($.isFunction(video[0].webkitEnterFullScreen)){
				video[0].webkitEnterFullScreen();
			}
			else if($.isFunction(video[0].mozRequestFullScreen)){
				video[0].mozRequestFullScreen();
			}
			else{
				alert("您的浏览器不支持全屏");
			}
		});
		
		//改变音量
		$(".sound").click(function(){
			video[0].muted = !video[0].muted;
			$(this).toggleClass("muted");
			if(video[0].muted){
				$(".volumeBar").css("width", 0);
			}else{
				$(".volumeBar").css("width",video[0].volume*100+"%");
			}
		});
        
        
        $(".sudu").mouseover(function(){
            $(".sudubox").show();
        });
        $(".sudubox").mouseleave(function(){
            $(".sudubox").hide();
        });
        
        //改变播放速度
        $('.btnx1').on('click', function() { 
            fastSpd(this);
            $(".sudubox").hide();
        });
        
        $('.btnx2').on('click', function() { 
            fastSpd(this);
            $(".sudubox").hide();
        });
        
        function fastSpd(obj){
            var spd = $(obj).text();
            var spdtext = spd.substring(1);
            //alert(spdtext);
            var sudu_first = $(".sudu").html();
            $(".sudu").html(spd);
            $(obj).html(sudu_first);
            video[0].playbackRate = spdtext;
		    video[0].play();
        }
       
		
		//视频可以播放时，让loading消失
		video.on("canplay", function(){
			$(".loading").fadeOut(100);
		});
		
		var completeloaded = false;
		
		video.on("canplaythrough", function(){
			completeloaded = true;
		});
		
		video.on("ended", function(){
			$(".btnPlay").removeClass("paused");
			video[0].pause();
		});
		
		//seeking-->寻找即要加载缓存时，显示转圈圈
		video.on("seeking", function(){
			if(!completeloaded){
				$(".loading").fadeIn(200);
			}
		});
		
		//已经找到
		video.on("seeked", function(){});
		
		//等待时让loading显示
		video.on("waiting", function(){
			$(".loading").fadeIn(200);
		});
		
		var timeDrag = false;	/* check for drag event */
		$('.progress').on('mousedown', function(e) {
			timeDrag = true;
			
			//alert(e.pageX+"-->"+$(".progress").offset().left);
			updatebar(e.pageX);
		});
		$(document).on('mouseup', function(e) {
			if(timeDrag) {
				timeDrag = false;
				updatebar(e.pageX);
			}
		});
		$(document).on('mousemove', function(e) {
			if(timeDrag) {
				updatebar(e.pageX);
			}
		});
		
		//更新进度条
		var updatebar = function(x) {
			var progress = $('.progress');
			
			var maxduration = video[0].duration;
			var position = x - progress.offset().left;
			var percentage = 100 * position / progress.width();
			if(percentage > 100) {
				percentage = 100;
			}
			if(percentage < 0) {
				percentage = 0;
			}
			$('.timeBar').css('width',percentage+'%');	
            $('.yuandian').css({"margin-left":percentage-0.2+'%'});
			video[0].currentTime = maxduration * percentage / 100;
			senCurtime = video[0].currentTime;
		};
        
        
        //根据已播放的时间设置进度条
        var updatebar1 = function(curtime){
			
			var maxduration = video[0].duration;
            var percentage = 100 * curtime / maxduration;
            if(percentage > 100) {
				percentage = 100;
			}
			if(percentage < 0) {
				percentage = 0;
			}
            $('.timeBar').css('width', percentage + '%'),
            $('.yuandian').css({"margin-left": percentage-0.2+'%'});
            video[0].currentTime = curtime;
            senCurtime = video[0].currentTime;
        }
        
        
		//改变播放速度
		var updatefastfowrd = function(obj, speed){
			$(".text").removeClass("selected");
			$(obj).addClass("selected");
			video[0].playbackRate = speed;
			video[0].play();
		}
		
		
		var volumeDrag = false;
		$('.volume').on('mousedown', function(e) {
			volumeDrag = true;
			video[0].muted = false;
			$('.sound').removeClass('muted');
			
			//alert(e.pageX+"-->"+$(".volume").offset().left);
			updateVolume(e.pageX);
		});
		$(document).on('mouseup', function(e) {
			if(volumeDrag) {
				volumeDrag = false;
				updateVolume(e.pageX);
			}
		});
		$(document).on('mousemove', function(e) {
			if(volumeDrag) {
				updateVolume(e.pageX);
			}
		});
		//设置音量的大小
		var updateVolume = function(x, vol){
			var volum = $(".volume");
			var percentage;
			
			if(vol){
				percentage = vol * 100;
			}else{
				var position1 = x - volum.offset().left;
				percentage = 100*position1 / volum.width();
			}
			
			if(percentage > 100) {
				percentage = 100;
			}
			if(percentage < 0) {
				percentage = 0;
			}
			
			$('.volumeBar').css('width',percentage+'%');	
			video[0].volume = percentage / 100;
			
			//change sound icon based on volume
			if(video[0].volume == 0){
				$('.sound').removeClass('sound2').addClass('muted');
			}
			else if(video[0].volume > 0.5){
				$('.sound').removeClass('muted').addClass('sound2');
			}
			else{
				$('.sound').removeClass('muted').removeClass('sound2');
			}
		};
		
		
		
		//视频缓存
		var startBuffer = function() {
			var currentBuffer = video[0].buffered.end(0);
			var maxduration = video[0].duration;
			var perc = 100 * currentBuffer / maxduration;
			$('.bufferBar').css('width',perc+'%');
				
			if(currentBuffer < maxduration) {
				setTimeout(startBuffer, 500);
			}
		};
		
		//将时间规范化
		var timeFormat1 = function(seconds){
			var m = Math.floor(seconds / 60)<10 ? "0"+Math.floor(seconds/60) : Math.floor(seconds/60);
			var s = Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));
			return m+":"+s;
		};
		
	});
    
    
        
    $("#comments").click(function(){
        $(".comments").show();
        $(".notes").hide();
        $(this).addClass("active").siblings("li").removeClass("active");
    });
    
    $("#notes").click(function(){
        $(".notes").show();
        $(".comments").hide();
        $(this).addClass("active").siblings("li").removeClass("active");
    }); 
    
    //屏幕可用工作区高度-------------//
    var height =window.innerHeight ;
    /*var header_height = $("header").height();
    var footer_box1 = $(".box1").height();
    var deleteheight = header_height+footer_box1;*/
   // alert(height+"-->"+header_height+"-->"+footer_box1);
    var h = (height-130);
   // alert(height+"-->"+h);
    $("section").css({"height":h+"px"});
    
    
    //当屏幕的大小发生改变时
    window.onresize = function(){
        var height =window.innerHeight ;
//        var header_height = $("header").height();
//        var footer_box1 = $(".box1").height();ss
//        var deleteheight = header_height+footer_box1;
        var h = (height-130);
       // alert(height+"-->"+h);
        $("section").css({"height":h+"px"});
    }